<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/11/2
 * Time: 9:37
 */

namespace app\common\model;


use app\common\model\sale\Gifts;
use think\Db;
use think\db\Query;
use think\Model;

/**
 * Class Sales
 * @package app\common\model
 *
 * @property integer sales_id
 * @property string sales_title
 * @property string sales_description
 * @property integer sales_type
 * @property integer sales_start_time
 * @property integer sales_end_time
 * @property string sales_discount
 * @property string sales_amount
 * @property string|Gifts gifts
 * @property string created
 * @property string updated
 * @property boolean disabled
 *
 */
class Sales extends Model
{
    protected $table = 'sales';
    protected $pk = 'sales_id';
    protected $field = [
        'sales_id',
        'sales_title',
        'sales_description',
        'sales_type',
        'sales_start_time',
        'sales_end_time',
        'sales_discount',
        'sales_amount',
        'disabled',
        'created',
        'updated',
        'gifts',
    ];

    private static $SaveFields = [
        'sales_id',
        'sales_title',
        'sales_description',
        'sales_type',
        'sales_start_time',
        'sales_end_time',
        'sales_discount',
        'sales_amount',
        'disabled',
    ];
    public static function getSaveFields() : array {
        return self::$SaveFields;
    }

    const TYPE_DISCOUNT = 1;
    const TYPE_CUT_PRICE = 2;
    const TYPE_GIFT = 3;
    const TypeNames = [
        self::TYPE_DISCOUNT     => '打折',
        self::TYPE_CUT_PRICE    => '减免',
        self::TYPE_GIFT         => '赠送',
    ];

    public function encodeJson() {
        if (isset($this->gifts)) {
            if (is_array($this->gifts) || is_object($this->gifts)) {
                $this->gifts = json_encode($this->gifts,JSON_UNESCAPED_UNICODE);
            }
        }
    }
    public function decodeJson() {
        if (isset($this->gifts)) {
            if (is_string($this->gifts)) {
                $this->gifts = json_decode($this->gifts);
            }
        }
    }

    public function save($data = [], $where = [], $sequence = null)
    {
        $this->encodeJson();
        if ($this->isUpdate) $this->updated = date('Y-m-d H:i:s');
        else $this->created = date('Y-m-d H:i:s');

        $result = parent::save($data, $where, $sequence);

        $this->decodeJson();

        return $result;
    }

    public static function get($data, $with = [], $cache = false)
    {
        $model = parent::get($data, $with, $cache);
        $model->decodeJson();
        return $model;
    }

    /**
     * 管理端列表
     *
     * @param int $page
     * @param int $rows
     * @param int $type
     * @return mixed
     */
    public static function manageList(int $page, int $rows, int $type = 0) {
        $list = self::all(function (Query $query) use ($page,$rows,$type) {
            if ($type > 0) {
                $query->where('sales_type','=', $type);
            }
            $query->page($page, $rows);
            $query->order('sales_id','desc');
        });

        foreach ($list as $item) {
            $item->decodeJson();
        }

        return $list;
    }

    /**
     * 设置禁用属性
     *
     * @param $id
     * @param $disabled
     * @return int
     */
    public static function setDisable($id, $disabled) {
        $sql = <<<SQL
UPDATE sales SET disabled=:disabled WHERE sales_id = :id
SQL;
        return Db::execute($sql, ['id' => $id, 'disabled' => $disabled]);
    }

    /**
     * 获取选择列表
     * @return mixed
     */
    public static function listAvailable() {
        $sql = <<<SQL
SELECT sales_id, sales_title FROM sales
WHERE disabled=FALSE 
SQL;
        $list = Db::query($sql);
        return $list;
    }

    public function isAvailable() {
        if ($this->disabled) return false;
        $now = time();
        return ($this->sales_start_time<$this->sales_end_time) && ($this->sales_start_time<$now) && ($this->sales_end_time>$now);
    }

    /**
     * @param $price
     * @param null $detail
     * @return array
     */
    public function finalPrice($price, $detail = null) {

        if (null !== $detail) $detail .= '，' . $this->sales_title;
        if (1 == $this->sales_type) {
            $discount = round($this->sales_discount * 0.01, 2);
            $price *= $discount;
            if (null !== $detail) $detail .= '，'. round($discount * 0.1, 1) .'折';
        } elseif (2 == $this->sales_type) {
            $price -= $this->sales_amount;
            if (null !== $detail) $detail .= '，减免￥' . $this->sales_amount;
        }

        return [
            'price' => $price,
            'detail' => $detail,
            'gifts' => $this->gifts
        ];
    }

    /**
     * 获取销售活动的赠送商品列表，简单列表
     *
     * @return mixed
     */
    public function getGiftsList() {
        $gifts = new \stdClass();
        foreach ($this->gifts as $field => $list) {
            $itemType = Gifts::getItemTypeId($field);
            $itemClass = BuyBill::getBuyItem($itemType);
            $gifts->$field = $itemClass::getSimpleList($list);
        }
        return $gifts;
    }
}